const webpack = require('webpack')
const electron = require('electron')
const mainConfig = require('./webpack.main')
const path = require('path')
const { spawn } = require('child_process')

let electronProcess = null
let manualRestart = false

function startElectron () {
  console.log('start electron')
  let args = [
    '--inspect=5858',
    path.join(__dirname, '../dist/main/main.js')
  ]

  if (process.env.npm_execpath.endsWith('yarn.js')) {
    args = args.concat(process.argv.slice(3))
  } else if (process.env.npm_execpath.endsWith('npm-cli.js')) {
    args = args.concat(process.argv.slice(2))
  }

  electronProcess = spawn(electron, args)

  electronProcess.stdout.on('data', data => {
    console.log(data.toString(), 'blue')
  })
  electronProcess.stderr.on('data', data => {
    console.log(data.toString(), 'red')
  })

  electronProcess.on('close', () => {
    if (!manualRestart) process.exit()
  })
}

function startMain () {
  return new Promise((resolve, reject) => {
    const compiler = webpack(mainConfig)

    compiler.hooks.watchRun.tapAsync('watch-run', (compilation, done) => {
      console.log('Main', 'compiling...')
      // hotMiddleware.publish({ action: 'compiling' })
      done()
    })
    // console.log(compiler)

    compiler.watch({}, (err, stats) => {
      if (err) {
        console.log(err)
        return
      }

      // console.log('Main', stats)
      // startElectron()
      // if (electronProcess && electronProcess.kill) {
      //   manualRestart = true
      //   process.kill(electronProcess.pid)
      //   electronProcess = null
      //   startElectron()
      //
      //   setTimeout(() => {
      //     manualRestart = false
      //   }, 5000)
      // }

      resolve()
    })
  })
}

function startRenderer () {
  spawn('../node_modules/.bin/vue-cli-service', ['serve'])
}

// startRenderer()

function init () {
  startMain()
    .then(() => {
      console.log('main finish')
      startElectron()
    })
}

init()
